package com.fingard.dsp.bank.directbank.icbc02;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheck;
import com.fingard.dsp.bank.reqrespobj.balancecheck.ReqBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.RetAtsBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.detail.RetAtsBalCheckDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by Lewis on 2017/6/5.
 */
public class ICBC02BalanceCheck extends ICBC02Base implements IBalanceCheck {
    //单个余额对账查询和批量余额对账查询，统一采用流处理方式
    //1、循环调用ReqBalCheckQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用RetAtsBalCheckQry.writeRetDetail()，写入返回ATS的明细
    @Override
    public RetAtsBalCheckQry d_7508_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        //余额对账查询返回ATS的对象
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = p_req7508.reqHeader.transSeqID;
            bnkTransCode = "YDZQRYBAL";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.1.0";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            Date dateFrom = p_req7508.getYearMonth();
            String dateTo = "";
            dateTo = dateConvert(dateFrom);
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("AccNo", p_req7508.actNum);
            if (dateTo != null && dateFrom != null) {
                xmlWriter.writeElementString("BeginDate", new SimpleDateFormat("yyyyMM").format(dateFrom) + "01");
                xmlWriter.writeElementString("EndDate", dateTo);
            }
            /*xmlWriter.writeElementString("TotalNum", String.valueOf(p_req7508.detailCount));
            xmlWriter.writeElementClosed("ReqReserved1");
            xmlWriter.writeElementClosed("ReqReserved2");//两个备用字段
            int rdCount=0;
            while(p_req7508.readRecord()){
                rdCount++;
                xmlWriter.writeStartElement("rd");
                xmlWriter.writeElementString("iSeqno", String.valueOf(rdCount));
                xmlWriter.writeElementString("AccNo", p_req7508.readedDetail.actNum);
                xmlWriter.writeElementClosed("ReqReserved3");
                xmlWriter.writeElementClosed("ReqReserved4");
                xmlWriter.writeEndElement();
            }*/
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//CMS
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            //模拟银行返回
            /*tmpStrRet[0] = "";
            tmpStrRet[1] = "<?xml version=\"1.0\"?>\n" +
                    "<CMS>\n" +
                    "\t<eb>\n" +
                    "\t\t<pub>\n" +
                    "\t\t\t<TransCode>YDZQRYBAL</TransCode>\n" +
                    "\t\t\t<CIS>12345</CIS>\n" +
                    "\t\t\t<BankCode>归属银行编号</BankCode>\n" +
                    "\t\t\t<ID>证书ID</ID>\n" +
                    "\t\t\t<TranDate>201705</TranDate>\n" +
                    "\t\t\t<TranTime>123456789</TranTime>\n" +
                    "\t\t\t<fSeqno>1</fSeqno>\n" +
                    "\t\t\t<RetCode>00000</RetCode>\n" +
                    "\t\t\t<RetMsg>交易返回描述</RetMsg>\n" +
                    "\t\t</pub>\n" +
                    "\t\t<out>\n" +
                    "\t\t\t<AccNo>" + p_req7508.actNum + "</AccNo>\n" +
                    "\t\t\t<BeginDate>20170501</BeginDate>\n" +
                    "\t\t\t<EndDate>20170531</EndDate>\n" +
                    "\t\t\t<rd>\n" +
                    "\t\t\t\t<VerifyCode>11</VerifyCode>\n" +
                    "\t\t\t\t<DZDNo>12678</DZDNo>\n" +
                    "\t\t\t\t<AcctType>2</AcctType>\n" +
                    "\t\t\t\t<CurrCode>1</CurrCode>\n" +
                    "\t\t\t\t<Balance>1234.55</Balance>\n" +
                    "\t\t\t\t<FixDate>定期存款存期</FixDate>\n" +
                    "\t\t\t\t<DeadDate>201705</DeadDate>\n" +
                    "\t\t\t\t<DepositNo>123</DepositNo>\n" +
                    "\t\t\t\t<DZFlag>1</DZFlag>\n" +
                    "\t\t\t\t<DeDZFlag>明细对帐情况（未达帐、疑义帐）</DeDZFlag>\n" +
                    "\t\t\t\t<BalanceFlag>余额调节表编制情况（已编制、未编制）</BalanceFlag>\n" +
                    "\t\t\t\t<UserRem>备注</UserRem>\n" +
                    "\t\t\t\t<CreditNo>借据号</CreditNo>\n" +
                    "\t\t\t\t<Corpus>123.00</Corpus>\n" +
                    "\t\t\t\t<BackInterest>23</BackInterest>\n" +
                    "\t\t\t\t<DebitDate>贷款到息日</DebitDate>\n" +
                    "\t\t\t\t<AcctName>户名</AcctName>\n" +
                    "\t\t\t\t<Drcrf>1</Drcrf>\n" +
                    "\t\t\t\t<DZGenDate>201705</DZGenDate>\n" +
                    "\t\t\t</rd>\n" +
                    "\t\t</out>\n" +
                    "\t</eb>\n" +
                    "</CMS>\n";*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                    RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                    tmpRetDetail.actNum = tmpBkReader.getFirstText("/CMS/eb/out/AccNo");
                    tmpRetDetail.dateFrom = tmpBkReader.getFirstText("/CMS/eb/out/BeginDate");
                    tmpRetDetail.dateTo = tmpBkReader.getFirstText("/CMS/eb/out/EndDate");
                    if (isActiveRetCode(tmpRetCode)) {
                        while (tmpBkReader.read("/CMS/eb/out/rd")) {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = tmpRetMsg;
                            tmpRetDetail.statementNumber = tmpBkReader.readedXElement.getSingleText("DZDNo");//对账单编号
                            tmpRetDetail.acctType = tmpBkReader.readedXElement.getSingleText("AcctType");//存款种类
                            tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrCode"));
                            tmpRetDetail.depositNo = tmpBkReader.readedXElement.getSingleText("DepositNo");
                            String dzFlag = tmpBkReader.readedXElement.getSingleText("DZFlag");
                            String atsFlag = "";
                            if ("1".equals(dzFlag)) {
                                atsFlag = "2";
                            } else if ("2".equals(dzFlag)) {
                                atsFlag = "3";
                            } else {//默认（0）和未对账（3）
                                atsFlag = "1";
                            }
                            tmpRetDetail.dzFlag = atsFlag;
                            tmpRetDetail.principal = tmpBkReader.readedXElement.getSingleText("Corpus");
                            tmpRetDetail.interestMoney = tmpBkReader.readedXElement.getSingleText("BackInterest");
                            tmpRetDetail.actName = tmpBkReader.readedXElement.getSingleText("AcctName");
                            tmpRetDetail.cdFlag = tmpBkReader.readedXElement.getSingleText("Drcrf");
                            tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("UserRem");
                            String tmpBalance = "";
                            if (tmpBkReader.readedXElement.getSingleText("Balance") != null) {
                                tmpBalance = tmpBkReader.readedXElement.getSingleText("Balance").trim();
                            }
                            if (tmpBalance.length() > 0) {
                                tmpRetDetail.actBal = StringHelper.amountDivide100(tmpBalance);
                            }
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}

